from flask import g, render_template, request, jsonify, session, current_app, abort

from info import db
from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS, USER_FOLLOWED_MAX_COUNT, \
    OTHER_NEWS_PAGE_MAX_COUNT
from info.models import Category, News, User
from info.modules.profile import profile_blue
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blue.route("/user_info")
@user_login_data
def base_info():
    user=g.user
    data={"user":user.to_dict() if user else None}
    return render_template("news/user.html",data=data)

@profile_blue.route("/user_base_info",methods=["post","get"])
@user_login_data
def user_base_info():
    user=g.user
    if request.method=="GET":
        data={
            "user":user
        }
        return render_template("news/user_base_info.html",data=data)

    nick_name=request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if gender not in ("MAN","WOMAN"):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    user.nick_name=nick_name
    user.signature=signature
    user.gender=gender
    session["nick_name"]=nick_name
    return jsonify(errno=RET.OK,errmsg="修改成功")

@profile_blue.route("/pic_info",methods=["post","get"])
@user_login_data
def pic_info():
    user=g.user
    if request.method=="GET":
        user=g.user
        data={"user":user.to_dict()}
        return render_template("news/user_pic_info.html",data=data)

    avatar=request.files.get("avatar").read()
    print(avatar)
    try:
        url=storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="图片上传错误")
    user.avatar_url=url
    data={
        "avatar_url":QINIU_DOMIN_PREFIX+url
    }
    return jsonify(errno=RET.OK,errmsg="上传成功",data=data)


@profile_blue.route("/pass_info",methods=["get","post"])
@user_login_data
def pass_info():
    user=g.user
    if request.method=="GET":
        return render_template("news/user_pass_info.html")
    old_password=request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR,errmsg="密码不正确")
    user.password=new_password
    return jsonify(errno=RET.OK,errmsg="密码修改正确")

@profile_blue.route("/collection")
@user_login_data
def user_collection():
    user=g.user
    p=request.args.get("p","1")
    try:
        p=int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        paginate=user.collection_news.paginate(p,USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")
    collections=paginate.items
    page=paginate.page
    pages=paginate.pages
    data={
        "collections":collections,
        "page":page,
        "pages":pages
    }
    return render_template("news/user_collection.html",data=data)


@profile_blue.route("/news_release",methods=["post","get"])
@user_login_data
def news_release():
    user=g.user
    if request.method=="GET":
        categories=Category.query.all()
        categories.pop(0)
        data={
            "categories":categories
        }
        return render_template("news/user_news_release.html",data=data)

    title=request.form.get("title")
    category_id=request.form.get("category_id")
    digest=request.form.get("digest")
    index_image=request.files.get("index_image")
    content=request.form.get("content")
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    try:
        index_image=index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR,errmsg="图片读取有误")
    try:
        url=storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="第三方错误")
    news=News()
    news.title=title
    news.content=content
    news.category_id=category_id
    news.digest=digest
    news.index_image_url=QINIU_DOMIN_PREFIX+url
    news.user_id=user.id
    news.status=1
    news.source="个人发布"
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库存储错误")
    return jsonify(errno=RET.OK,errmsg="发布成功")


@profile_blue.route("/news_list")
@user_login_data
def new_list():
    user = g.user
    p = request.args.get("p", "1")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(p,USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    collections = paginate.items
    page = paginate.page
    pages = paginate.pages
    data = {
        "collections": collections,
        "page": page,
        "pages": pages
    }
    return render_template("news/user_news_list.html",data=data)


@profile_blue.route("/user_follow")
@user_login_data
def user_follow():
    user=g.user
    p=request.args.get("p","1")
    try:
        p=int(p)
    except Exception as e:
        p=1
        current_app.logger.error(e)
    followed_list=[]
    page=1
    pages=1
    try:
        paginate=user.followed.paginate(p,USER_FOLLOWED_MAX_COUNT,False)
        followed_list=paginate.items
        page=paginate.page
        pages=paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    new_followed_list=[]
    for followed in followed_list:
        new_followed_list.append(followed.to_dict())
    data={
        "users":new_followed_list,
        "page":page,
        "pages":pages
    }
    return render_template("news/user_follow.html",data=data)

@profile_blue.route("/other_info")
@user_login_data
def other_info():
    user=g.user
    other_id=request.args.get("id")
    if not other_id:
        abort(404)
    try:
        other_id=int(other_id)
    except Exception as e:
        current_app.logger.error(e)
    other=None #type:User
    try:
        other=User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not other:
        abort(404)
    is_followed=False
    if user:
        if other.followers.filter(User.id==user.id).count():
            is_followed=True
    data={
        "other_info":other.to_dict(),
        "user":user.to_dict(),
        "is_followed":is_followed
    }
    return render_template("news/other.html",data=data)



@profile_blue.route("/other_news_list")
@user_login_data
def other_news_list():
    user=g.user
    p=request.args.get("p")
    user_id=request.args.get("user_id")
    print(p,user_id)
    if not all([p,user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    try:
        p=int(p)
        user_id=int(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    other=None # type:User
    try:
        other=User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")
    if not other:
        return jsonify(errno=RET.NODATA,errmsg="没有这条数据")
    news_list=None
    page=1
    pages=1
    try:
        paginate=other.news_list.paginate(p,OTHER_NEWS_PAGE_MAX_COUNT,False)
        news_list=paginate.items
        page=paginate.page
        pages=paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")
    new_news_list=[]
    for news in news_list:
        new_news_list.append(news.to_dict())
    data={
        "news_list":new_news_list,
        "current_page":page,
        "total_page":pages
          }
    return jsonify(errno=RET.OK,errmsg="OK",data=data)



